package com.dzx.currentency.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月20日 11:17:04
 */

/**
 *  一般用于多个线程之间相互等待，当全部都到达某个屏障点的时候在，继续执行每个线程,并且可以重复循环使用
 *   线程名称              某个屏障点        终点
 *   thread1  ------------| ---------- end
 *   thread2  ------------| ---------- end
 *   thread3  ------------| ---------- end
 *   thread4  ------------| ---------- end
 *   thread5  ------------| ---------- end
 *
 */
@Slf4j
public class CyclicBarrierExample1 {

//    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5,() -> {
           log.info("五个线程都已经准备就绪");
   });

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            final int threadNum = i;
            Thread.sleep(1000);
            service.execute(() -> {
                try {
                    race(threadNum);
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        service.shutdown();
    }

    private static void race(int threadNum) throws InterruptedException, BrokenBarrierException {
        Thread.sleep(1000);
        log.info("{} is ready", threadNum);
        cyclicBarrier.await();
        try {
       //     cyclicBarrier.await(1, TimeUnit.SECONDS);
        } catch (Exception e) {
         //   e.printStackTrace();
        }
        log.info("{} continue", threadNum);
    }
}
